<template>
  <div class="answer-questionnaire">
    <div v-if="loading" class="loading">正在加载问卷...</div>
    <div v-if="error" class="error">{{ error }}</div>
    <div v-if="submitSuccess" class="success">回答提交成功！</div>
    
    <div v-if="questionnaire.title && !loading">
      <h1>{{ questionnaire.title }}</h1>
      <p v-if="questionnaire.description" class="description">{{ questionnaire.description }}</p>
      
      <form @submit.prevent="submitResponse">
        <div 
          v-for="(question, index) in questionnaire.questions" 
          :key="index"
          class="question-item"
        >
          <label class="question-label">{{ index + 1 }}. {{ question.content }}</label>
          
          <!-- 单选题 -->
          <div v-if="question.type === 'radio'" class="radio-options">
            <div v-for="(option, oIndex) in question.options" :key="oIndex" class="radio-option">
              <input 
                type="radio" 
                :id="`question-${index}-option-${oIndex}`" 
                :name="`question-${index}`" 
                :value="option"
                v-model="userResponses[index]" 
                required
              />
              <label :for="`question-${index}-option-${oIndex}`">{{ option }}</label>
            </div>
          </div>
          
          <!-- 多选题 -->
          <div v-else-if="question.type === 'checkbox'" class="checkbox-options">
            <div v-for="(option, oIndex) in question.options" :key="oIndex" class="checkbox-option">
              <input 
                type="checkbox" 
                :id="`question-${index}-option-${oIndex}`" 
                :value="option"
                v-model="userResponses[index]" 
              />
              <label :for="`question-${index}-option-${oIndex}`">{{ option }}</label>
            </div>
          </div>
          
          <!-- 填空题 -->
          <div v-else-if="question.type === 'text'" class="text-input">
            <input 
              type="text" 
              v-model="userResponses[index]" 
              placeholder="请输入您的回答" 
              required
              class="form-control"
            />
          </div>
        </div>
        
        <button 
          type="submit" 
          class="btn btn-primary"
          :disabled="submitting || !isFormValid"
        >
          {{ submitting ? '提交中...' : '提交回答' }}
        </button>
      </form>
    </div>
  </div>
</template>
  
<script>
import { defineComponent, ref, reactive, onMounted, computed } from 'vue';
import { useRoute } from 'vue-router';

export default defineComponent({
  setup() {
    const route = useRoute();
    const questionnaire = reactive({
      title: '',
      description: '',
      questions: []
    });
    const userResponses = ref([]);
    const loading = ref(true);
    const submitting = ref(false);
    const error = ref('');
    const submitSuccess = ref(false);
    
    // 检查表单是否有效
    const isFormValid = computed(() => {
      if (userResponses.value.length !== questionnaire.questions.length) {
        return false;
      }
      
      for (let i = 0; i < questionnaire.questions.length; i++) {
        const question = questionnaire.questions[i];
        const response = userResponses.value[i];
        
        // 检查必填项
        if (question.type === 'radio' && !response) {
          return false;
        }
        
        if (question.type === 'checkbox' && (!response || response.length === 0)) {
          return false;
        }
        
        if (question.type === 'text' && !response) {
          return false;
        }
      }
      
      return true;
    });
    
    const fetchQuestionnaire = async () => {
      const id = route.params.id;
      loading.value = true;
      error.value = '';
      
      try {
        const response = await fetch(`http://localhost:9001/api/questionnaires/${id}`);
        if (!response.ok) {
          throw new Error('获取问卷失败');
        }
        
        const data = await response.json();
        Object.assign(questionnaire, data);
        
        // 初始化回答数组，根据问题类型设置默认值
        userResponses.value = questionnaire.questions.map(question => {
          if (question.type === 'checkbox') {
            return []; // 多选题初始为空数组
          } else {
            return ''; // 单选题和填空题初始为空字符串
          }
        });
      } catch (err) {
        console.error('获取问卷时出错:', err);
        error.value = '加载问卷失败: ' + err.message;
      } finally {
        loading.value = false;
      }
    };
    
    const submitResponse = async () => {
      if (!isFormValid.value) {
        error.value = '请回答所有问题';
        return;
      }
      
      submitting.value = true;
      error.value = '';
      submitSuccess.value = false;
      
      try {
        // 直接使用原始的回答数组
        const response = {
          questionnaireId: questionnaire.id,
          userId: 1, // 假设用户ID为1，实际应用中应动态获取
          answers: userResponses.value
        };
        
        const result = await fetch('http://localhost:9001/api/user-responses', {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json'
          },
          body: JSON.stringify(response)
        });
        
        if (!result.ok) {
          throw new Error('提交回答失败');
        }
        
        const data = await result.json();
        console.log('回答提交成功:', data);
        submitSuccess.value = true;
        
        // 重置回答
        userResponses.value = questionnaire.questions.map(question => {
          if (question.type === 'checkbox') {
            return []; // 多选题初始为空数组
          } else {
            return ''; // 单选题和填空题初始为空字符串
          }
        });
        
        // 3秒后隐藏成功消息
        setTimeout(() => {
          submitSuccess.value = false;
        }, 3000);
      } catch (err) {
        console.error('提交回答时出错:', err);
        error.value = '提交失败: ' + err.message;
      } finally {
        submitting.value = false;
      }
    };
    
    onMounted(fetchQuestionnaire);
    
    return {
      questionnaire,
      userResponses,
      loading,
      submitting,
      error,
      submitSuccess,
      isFormValid,
      submitResponse
    };
  }
});
</script>

<style scoped>
.answer-questionnaire {
  max-width: 800px;
  margin: 0 auto;
  padding: 20px;
}

.description {
  color: #666;
  margin-bottom: 20px;
}

.question-item {
  margin-bottom: 30px;
  padding: 15px;
  border: 1px solid #eee;
  border-radius: 4px;
  background-color: #f9f9f9;
}

.question-label {
  display: block;
  margin-bottom: 12px;
  font-weight: 500;
  font-size: 1.1em;
}

.radio-options, .checkbox-options {
  margin-top: 10px;
}

.radio-option, .checkbox-option {
  margin-bottom: 8px;
  display: flex;
  align-items: center;
}

.radio-option label, .checkbox-option label {
  margin-left: 8px;
  cursor: pointer;
}

.text-input {
  margin-top: 10px;
}

.form-control {
  width: 100%;
  padding: 8px;
  border: 1px solid #ddd;
  border-radius: 4px;
}

.btn {
  padding: 8px 16px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  margin-top: 20px;
}

.btn-primary {
  background-color: #4CAF50;
  color: white;
}

.btn:disabled {
  background-color: #cccccc;
  cursor: not-allowed;
}

.loading, .error, .success {
  padding: 10px;
  margin-bottom: 15px;
  border-radius: 4px;
}

.loading {
  background-color: #f9f9f9;
}

.error {
  background-color: #ffebee;
  color: #c62828;
}

.success {
  background-color: #e8f5e9;
  color: #2e7d32;
}
</style>